<!--
 * @Author: songxinfeng
 * @Date: 2025/1/15
 * @Description: CRM系统顶部导航栏组件
-->
<template>
  <div class="header-bar">
    <div class="header-left">
      <el-button type="text" @click="toggleCollapse">
        <el-icon><Fold v-if="!isCollapse" /><Expand v-else /></el-icon>
      </el-button>
      <span class="system-title">易客通CRM系统</span>
    </div>
    <div class="header-right">
      <span class="username" v-if="username">{{ username }}</span>
      <el-dropdown @command="handleCommand">
        <span class="user-info">
          <el-icon><UserFilled /></el-icon>
          <el-icon><ArrowDown /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Fold, Expand, ArrowDown, UserFilled } from '@element-plus/icons-vue'

const router = useRouter()
const username = ref('')
const isCollapse = ref(false)

onMounted(() => {
  // 从localStorage获取用户信息
  const user = localStorage.getItem('user')
  if (user) {
    try {
      const userData = JSON.parse(user)
      username.value = userData.realName || userData.username || ''
    } catch (e) {
      console.error('解析用户信息失败:', e)
    }
  }
})

const handleCommand = (command: string) => {
  if (command === 'logout') {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push('/login')
    ElMessage.success('退出成功')
  }
}

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
  // 这里可以通过事件总线或者状态管理来通知侧边栏折叠状态
}
</script>

<style scoped>
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  width: 100%;
  padding: 0 20px;
  margin: 0;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  height: 100%;
}

.system-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
  height: 100%;
}

.username {
  color: #606266;
  font-size: 14px;
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #606266;
  gap: 4px;
  height: 100%;
}

.user-info:hover {
  color: #409eff;
}
</style>
